package com.crm.business.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.crm.business.admin.service.*;
import com.crm.common.admin.entity.BO.AdminUserBO;
import com.crm.common.admin.entity.PO.AdminConfig;
import com.crm.common.admin.entity.PO.AdminModelSort;
import com.crm.common.admin.entity.PO.AdminRole;
import com.crm.common.admin.entity.PO.AdminUser;
import com.crm.common.admin.entity.VO.AdminUserVO;
import com.crm.common.auth.entity.AdminUserStatusUpdateBO;
import com.crm.common.ka.core.common.BaseStatusEnum;
import com.crm.common.ka.core.common.DataAuthEnum;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.common.ka.core.entity.UserInfo;
import com.crm.common.ka.core.feign.admin.entity.*;
import com.crm.business.utils.UserCacheUtil;
import com.crm.business.utils.UserUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class AdminServiceCallImpl implements AdminService {

    @Autowired
    private IAdminUserService adminUserService;
    @Autowired
    private IAdminDeptService adminDeptService;
    @Autowired
    private IAdminConfigService adminConfigService;
    @Autowired
    private IAdminRoleService adminRoleService;
    @Autowired
    private IAdminModelSortService adminModelSortService;
    @Autowired
    private IAdminMessageService messageService;
    @Autowired
    private IAdminMenuService adminMenuService;
    @Autowired
    private IAdminUserManageDeptService adminUserManageDeptService;


    /**
     * 根据用户ID获取用户信息
     *
     * @param userId 用户ID
     * @return data
     */
    public UserInfo getUserInfo(Long userId){
        AdminUser byId = adminUserService.getById(userId);
        UserInfo userInfo = null;
        if (byId != null && byId.getDeptId() != null) {
            userInfo = BeanUtil.copyProperties(byId, UserInfo.class);
            String nameByDeptId = UserCacheUtil.getDeptName(byId.getDeptId());
            userInfo.setDeptName(nameByDeptId);
            userInfo.setRoles(adminUserService.queryUserRoleIds(userInfo.getUserId()));
        }
        return userInfo;
    }

    /**
     * 根据用户ID获取用户名
     *
     * @param userId 用户ID
     * @return data
     */
    public String queryUserName( Long userId){
        return adminUserService.getNameByUserId(userId);
    }


    /**
     * 根据部门ID获取部门名称
     *
     * @param deptId 部门ID
     * @return 结果信息
     */
    public String queryDeptName(Integer deptId){
        return adminDeptService.getNameByDeptId(deptId);
    }

    /**
     * 根据组织Id获取所有上级名称
     * @param deptId
     * @return
     */
    public String queryAllDeptNameByDeptId( Integer deptId){
        return adminDeptService.queryAllDeptNameByDeptId(deptId);
    }

    /**
     * 查询部门下属部门
     *
     * @param deptId 上级ID
     * @return data
     */
    public  List<Integer> queryChildDeptId(Integer deptId){
        return adminDeptService.queryChildDept(deptId);
    }

    /**
     * 查询该用户下级的用户
     *
     * @param userId 用户ID 0代表全部
     * @return data
     */
    public List<Long> queryChildUserId( Long userId){
        List<Long> longList = adminUserService.queryChildUserId(userId);
        return longList;
    }

    /**
     * 查询企业所有用户
     *
     * @return data
     */
    public List<Long> queryUserList(){
        List<AdminUserVO> adminUserBOList = adminUserService.queryUserList(null).getList();
        return adminUserBOList.stream().map(AdminUserVO::getUserId).collect(Collectors.toList());
    }

    /**
     * 根据名称查询系统配置
     *
     * @param name 名称
     * @return data
     */
    public List<AdminConfigBo> queryConfigByName(String name){
        List<AdminConfig> adminConfigs = adminConfigService.queryConfigListByName(name);
        return adminConfigs.stream().map(config -> BeanUtil.copyProperties(config, AdminConfigBo.class)).collect(Collectors.toList());
    }

    /**
     * 根据名称查询系统配置
     *
     * @param name 名称
     * @return data
     */
    public AdminConfigBo queryFirstConfigByName(String name){
        AdminConfig config = adminConfigService.queryConfigByName(name);
        return BeanUtil.copyProperties(config, AdminConfigBo.class);
    }


    /**
     * 根据ids查询用户信息
     *
     * @param ids id列表
     * @return data
     */
    public List<SimpleUser> queryUserByIds(List<Long> ids){
        List<SimpleUser> simpleUsers = adminUserService.queryUserByIds(ids);
        return simpleUsers;
    }


    /**
     * 根据ids查询角色信息
     *
     * @param ids id列表
     * @return data
     */
    public List<SimpleRole> queryRoleByIds( List<Long> ids){
        List<SimpleRole> simpleRoles = adminRoleService.queryRoleByIds(ids);
        return simpleRoles;
    }





    /**
     * 根据ids查询正常的用户Id
     *
     * @param ids id列表
     * @return data
     */
    public List<Long> queryNormalUserByIds( List<Long> ids){
        return adminUserService.queryNormalUserByIds(ids);
    }
    /**
     * 根据ids查询用户信息
     *
     * @param userId id
     * @return data
     */
    public SimpleUser queryUserById( Long userId){
        AdminUser adminUser = adminUserService.getById(userId);
        return BeanUtil.copyProperties(adminUser, SimpleUser.class);
    }

    /**
     * 根据ids查询部门信息
     *
     * @param ids id列表
     * @return data
     */
    public List<SimpleDept> queryDeptByIds(List<Integer> ids){
        List<SimpleDept> simpleDepts = adminDeptService.queryDeptByIds(ids);
        return simpleDepts;
    }

    /**
     * 根据ids查询部门下的用户
     *
     * @param ids id列表
     * @return data
     */
    public List<Long> queryUserByDeptIds( List<Integer> ids){
        List<Long> userIds = adminUserService.queryUserByDeptIds(ids);
        return userIds;
    }

    /**
     * 根据ids查询部门下的启用状态用户
     *
     * @param ids id列表
     * @return data
     */
    public  List<Long> queryEnableUserByDeptIds( List<Integer> ids){
        List<Long> userIds = adminUserService.queryEnableUserByDeptIds(ids);
        return userIds;
    }

    /**
     * 根据部门ids查询有效用户列表
     *
     * @param ids id列表
     * @return data
     */
    public  List<Long> queryNormalUserByDeptIds( List<Integer> ids){
        List<Long> userIds = adminUserService.queryNormalUserByDeptIds(ids);
        return userIds;
    }

    /**
     * 查询数据权限
     * @param userId 用户ID
     * @param menuId 菜单ID
     * @return 权限
     */
    public Integer queryDataType( Long userId,  Integer menuId){
        Integer dataType = adminRoleService.queryDataType(userId, menuId);
        return dataType;
    }



    /**
     * 查询数据权限
     * @param userId 用户ID
     * @param menuId 菜单ID
     * @return 权限
     */
    public Integer queryMaxDataType( Long userId,  Integer menuId){
        Integer dataType = adminRoleService.queryMaxDataType(userId, menuId);
        return dataType;
    }

    /**
     * 查询权限内用户
     * @param userId 用户ID
     * @param realm 菜单标识
     * @return 权限
     */
    public List<Long>  queryUserByAuth( Long userId,  String realm){
        List<Long> longs = adminRoleService.queryUserByAuth(userId, realm);
        return longs;
    }

    public Integer queryWorkRole( Integer label){
        Integer role = adminRoleService.queryWorkRole(label);
        return role;
    }

    /**
     * 根据角色类型查询角色
     * @param type 角色类型
     * @return  type
     */
    public List<Integer> queryRoleByRoleType( Integer type){
        List<AdminRole> recordList = adminRoleService.lambdaQuery().select(AdminRole::getRoleId).eq(AdminRole::getIsSuper, BaseStatusEnum.CLOSE.getStatus().toString()).list();
        return recordList.stream().map(AdminRole::getRoleId).collect(Collectors.toList());
    }

    /**
     * 查询当前用户在某个模块下的角色
     * @param type 角色类型
     * @return
     */
    public List<AdminRole> queryRoleByRoleTypeAndUserId( Integer type){
        List<AdminRole> recordList = adminRoleService.queryRoleByRoleTypeAndUserId(type);
        return recordList;
    }

    /**
     * 修改系統配置
     *
     * @param adminConfig 配置实体
     * @return data
     */
    public void updateAdminConfig(@RequestBody AdminConfigBo adminConfig){
        AdminConfig config = new AdminConfig();
        BeanUtil.copyProperties(adminConfig,config);
        adminConfigService.updateAdminConfig(config);
        return ;
    }

    @ApiOperation("角色权限")
    public JSONObject auth(){
        JSONObject object = adminRoleService.auth(UserUtil.getUserId());
        AdminModelSort one = adminModelSortService.lambdaQuery().select(AdminModelSort::getModel).eq(AdminModelSort::getType, 1).eq(AdminModelSort::getUserId, UserUtil.getUserId()).orderByAsc(AdminModelSort::getSort).last(" limit 1").one();
        object.put("firstModel", one != null ? one.getModel() : "");
        return object;
    }

    public Long saveOrUpdateMessage( com.crm.common.ka.core.feign.admin.entity.AdminMessage message){
        Long messageId = messageService.saveOrUpdateMessage(message);
        return messageId;
    }

    public AdminMessage getMessageById(@PathVariable Long messageId){
        AdminMessage adminMessage = messageService.getById(messageId);
        return adminMessage;
    }

    public AdminConfigBo queryFirstConfigByNameAndValue(String name, String value){
        AdminConfig config = adminConfigService.queryFirstConfigByNameAndValue(name, value);
        return BeanUtil.copyProperties(config, AdminConfigBo.class);
    }

    public Integer queryMenuId( String realm1,  String realm2,  String realm3){
        Integer menuId = adminMenuService.queryMenuId(realm1,realm2,realm3);
        return menuId;
    }

    public List<Long> queryUserIdByRealName( List<String> realNames){
        List<Long> userIdList = adminUserService.queryUserIdByRealName(realNames);
        return userIdList;
    }

    public UserInfo queryLoginUserInfo( Long userId){
        UserInfo userInfo = adminUserService.queryLoginUserInfo(userId);
        return userInfo;
    }

    public Long queryUserIdByUserName( String userName){
        Long userId = adminUserService.lambdaQuery().select(AdminUser::getUserId).eq(AdminUser::getUsername, userName).oneOpt().map(AdminUser::getUserId).orElse(0L);
        return userId;
    }

    public Integer queryHrmDataAuthType( Integer menuId){
        if (UserUtil.isAdmin()){
            return DataAuthEnum.ALL.getValue();
        }
        Integer dataAuthType =adminRoleService.queryHrmDataAuthType(menuId);
        return Optional.ofNullable(dataAuthType).orElse(0);
    }

    public List<UserInfo> queryUserInfoList(){
        List<UserInfo> userInfoList = adminUserService.queryAllUserInfoList();
        return userInfoList;
    }

    public BasePage<AdminUserEntityVO> queryUserList(AdminUserBO adminUserBO){
        BasePage<AdminUserVO> page =  adminUserService.queryUserList(adminUserBO);
        BasePage<AdminUserEntityVO> resultPage = new BasePage<>();
        BeanUtil.copyProperties(page,resultPage);
        List<AdminUserEntityVO> list = new ArrayList<>();
        for(AdminUserVO vo : page.getList()){
            AdminUserEntityVO rvo = new AdminUserEntityVO();
            BeanUtil.copyProperties(vo,rvo);
            list.add(rvo);
        }
        resultPage.setList(list);
        return resultPage;
    }




    public List<Long> queryUserListByRoleIds( long[] ids){
        return adminUserService.queryUserListByRoleIds(ids);
    }

    public  List<Long>  queryUserListByDeptIds( long[] ids){
        return adminUserService.queryUserListByDeptIds(ids);
    }

    public List<Long> queryChannelSales(){
        List<Long> ids = adminUserService.queryChannelSales();
        return ids;
    }

    public List<AdminRole> queryRoleListByUserId(List<Long> userIds){
        return adminRoleService.queryRoleListByUserId(userIds);
    }

    /**
     * 根据部门Pid 获取下一级部门
     *
     * @param deptId 部门ID
     * @return 结果信息
     */
    public List<Integer> queryDeptByPid(Integer deptId){
        return adminDeptService.queryDeptByPid(deptId);
    }

    public List<Long> queryUserIdsByRoleIds(){
        return adminRoleService.queryUserIdsByRoleIds();
    }

    public List<Map<String, Object>> findByUsername(String username){
        List<Map<String, Object>> userInfoList = adminUserService.findByUsername(username);
        return userInfoList;
    }

    public List<Integer> queryUserRoleIds( Long userId){
        return adminUserService.queryUserRoleIds(userId);
    }

    public void setUserStatus(AdminUserStatusUpdateBO adminUserStatusBO){

        com.crm.common.admin.entity.BO.AdminUserStatusBO bo = new com.crm.common.admin.entity.BO.AdminUserStatusBO();
        BeanUtil.copyProperties(adminUserStatusBO,bo);
        adminUserService.setUserStatus(bo);
    }

   public List<String> queryNoAuthMenu( Long userId){
       return adminRoleService.queryNoAuthMenu(userId);
    }


    public List<Long> queryUserIdsByManageDept(){
       return adminUserManageDeptService.queryUserIdsByManageDept();
    }

}
